import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:get/get.dart';

class TestQuestionsLogic extends BaseController {
  // 从参数中获取测试ID和测试详情
  final int testId = Get.arguments?['testId'] ?? 0;
  final int userTestId = Get.arguments?['userTestId'] ?? 0;
  final ModelTestDetail testDetail =
      Get.arguments?['testDetail'] ?? ModelTestDetail();

  // 当前问题索引
  final currentQuestionIndex = 0.obs;

  // 用户答案
  final userAnswers = <int, List<int>>{}.obs;

  // 滑动打分题的问题ID到当前值的映射
  // final ratingValues = <int, int>{}.obs;

  // 排序题的排序选项列表
  // final rankingOptions = <ModelTestDetailQuestionsOptions>[].obs;

  // 多选题的已选选项ID列表
  final selectedOptionIds = <int, List<int>>{}.obs;

  // 所有问题
  late List<ModelTestDetailQuestions> questions;

  // 问题总数
  int get totalQuestions => questions.length;

  // 当前问题
  ModelTestDetailQuestions? get currentQuestion =>
      questions.isNotEmpty && currentQuestionIndex.value < questions.length
          ? questions[currentQuestionIndex.value]
          : null;

  // 是否是最后一题
  bool get isLastQuestion => currentQuestionIndex.value >= totalQuestions - 1;

  // 是否是第一题
  bool get isFirstQuestion => currentQuestionIndex.value <= 0;

  @override
  void onInit() {
    super.onInit();
    questions = testDetail.questions?.where((q) => q != null).toList() ?? [];

    // if (questions.isEmpty) {
    //   doError('没有可用的测试题目');
    // } else {
    //   // doFinished();
    //
    //   // 根据第一题的类型进行初始化
    //   if (currentQuestion?.type == 4) {
    //     // 排序题
    //     // initRankingOptions();
    //     initSelectedOptions();
    //   } else if (currentQuestion?.type == 6) {
    //     // 情绪选择器
    //     initSelectedOptions();
    //   }
    // }
  }

  // 选择答案（单选题）
  void selectAnswer(int optionId) {
    if (currentQuestion == null) return;
    int questionId = currentQuestion!.id!;
    userAnswers[questionId] = [optionId];
    update();
  }

  // 选择多个答案（多选题）
  void toggleAnswer(int optionId) {
    if (currentQuestion == null) return;

    int questionId = currentQuestion!.id!;

    // 初始化答案列表（如果不存在）
    if (!userAnswers.containsKey(questionId) ||
        userAnswers[questionId] == null) {
      userAnswers[questionId] = <int>[];
    }

    List<int> selectedOptions = List<int>.from(userAnswers[questionId] ?? []);
    // 切换选项状态
    if (selectedOptions.contains(optionId)) {
      selectedOptions.remove(optionId);
    } else {
      selectedOptions.add(optionId);
    }
    userAnswers[questionId] = selectedOptions;
    update();
  }

  // 设置滑动打分值
  void setRatingValue(int value) {
    // 确保问题存在且有选项
    // final question = questions.firstWhere((q) => q.id == questionId,
    //                                     orElse: () => ModelTestDetailQuestions());
    // if (question.id == null || question.options == null || question.options!.isEmpty) return;
    int questionId = currentQuestion!.id!;
    userAnswers[questionId] = [value];
    // 更新显示值
    // ratingValues[questionId] = value;
    //
    // // 获取选项ID
    // int optionId = question.options![0].id!;
    //
    // // 创建答案对象，保存选项ID和score值
    // userAnswers[questionId] = {
    //   'optionId': optionId,
    //   'score': value
    // };

    update();
  }

  // 初始化排序选项
  // void initRankingOptions() {
  //   if (currentQuestion == null || currentQuestion!.options == null) return;
  //
  //   int questionId = currentQuestion!.id!;
  //
  //   // 检查是否已有排序答案
  //   if (userAnswers.containsKey(questionId) &&
  //       userAnswers[questionId] is List<ModelTestDetailQuestionsOptions>) {
  //     rankingOptions.value =
  //         List<ModelTestDetailQuestionsOptions>.from(userAnswers[questionId]);
  //   } else {
  //     // 随机打乱选项顺序
  //     rankingOptions.value =
  //         List<ModelTestDetailQuestionsOptions>.from(currentQuestion!.options!)
  //           ..shuffle();
  //     userAnswers[questionId] = rankingOptions;
  //   }
  // }

  // // 重新排序选项
  // void reorderOptions(int oldIndex, int newIndex) {
  //   if (currentQuestion == null) return;
  //
  //   int questionId = currentQuestion!.id!;
  //
  //   // 确保列表已初始化
  //   // if (rankingOptions.isEmpty) {
  //   //   initRankingOptions();
  //   // }
  //
  //   // 处理拖动逻辑
  //   final item = rankingOptions.removeAt(oldIndex);
  //
  //   // 如果newIndex > oldIndex，newIndex需要减1，因为删除了一个元素
  //   if (newIndex > oldIndex) {
  //     rankingOptions.insert(newIndex - 1, item);
  //   } else {
  //     rankingOptions.insert(newIndex, item);
  //   }
  //
  //   // 保存排序后的答案
  //   userAnswers[questionId] =
  //       List<ModelTestDetailQuestionsOptions>.from(rankingOptions);
  //   update();
  // }

  // 判断选项是否被选中（单选）
  // bool isOptionSelected(int optionId) {
  //   if (currentQuestion == null) return false;
  //
  //   int questionId = currentQuestion!.id!;
  //   return userAnswers[questionId] == optionId;
  // }

  // 判断选项是否被选中
  bool isOptionMultiSelected(int optionId) {
    if (currentQuestion == null) return false;

    int questionId = currentQuestion!.id!;
    List<int> selectedOptions = List<int>.from(userAnswers[questionId] ?? []);
    return selectedOptions.contains(optionId);
  }

  // // 获取指定问题的滑动打分值
  // int getRatingValue(int questionId) {
  //   // 如果已经有缓存的值，直接返回
  //   if (ratingValues.containsKey(questionId)) {
  //     return ratingValues[questionId]!;
  //   }
  //
  //   // 查找问题
  //   final question = questions.firstWhere((q) => q.id == questionId,
  //                                       orElse: () => ModelTestDetailQuestions());
  //   if (question.id == null || question.options == null || question.options!.isEmpty) return 5;
  //
  //   // 检查是否已有答案
  //   if (userAnswers.containsKey(questionId)) {
  //     // 如果是新格式（包含optionId和score）
  //     if (userAnswers[questionId] is Map) {
  //       final score = userAnswers[questionId]['score'] as int;
  //       ratingValues[questionId] = score; // 缓存值
  //       return score;
  //     }
  //     // 兼容旧格式（直接存储value）
  //     else if (userAnswers[questionId] is int) {
  //       final score = userAnswers[questionId] as int;
  //       ratingValues[questionId] = score; // 缓存值
  //       return score;
  //     }
  //   }
  //
  //   // 初始化为5（中间值）
  //   int optionId = question.options![0].id!;
  //   userAnswers[questionId] = {
  //     'optionId': optionId,
  //     'score': 5
  //   };
  //   ratingValues[questionId] = 5; // 缓存值
  //   return 5;
  // }

  // // 初始化多选选项
  // void initSelectedOptions() {
  //   if (currentQuestion == null) return;
  //
  //   int questionId = currentQuestion!.id!;
  //
  //   // 如果已经有选择，则不需要初始化
  //   if (selectedOptionIds.containsKey(questionId)) return;
  //
  //   // 根据问题类型初始化不同的选项
  //   if (currentQuestion!.type == 2) { // 多选题
  //     selectedOptionIds[questionId] = [];
  //   } else if (currentQuestion!.type == 3) { // 滑动打分题
  //     // 滑动打分题使用ratingValues，不需要在这里初始化
  //   } else if (currentQuestion!.type == 4) { // 排序题
  //     // 排序题初始化为所有选项的ID列表，按原始顺序
  //     if (currentQuestion!.options != null) {
  //       List<int> optionIds = currentQuestion!.options!
  //           .where((option) => option.id != null)
  //           .map((option) => option.id!)
  //           .toList();
  //       selectedOptionIds[questionId] = optionIds;
  //     } else {
  //       selectedOptionIds[questionId] = [];
  //     }
  //   } else if (currentQuestion!.type == 5) { // 图片选择题
  //     selectedOptionIds[questionId] = [];
  //   } else if (currentQuestion!.type == 7) { // 百分比分配题
  //     // 百分比分配题由PercentageAllocationWidget内部处理
  //     // 这里不需要特殊初始化
  //   }
  // }

  // 前往下一题
  void nextQuestion() {
    clog('userAnswers  $userAnswers');

    if (currentQuestionIndex.value < totalQuestions - 1) {
      currentQuestionIndex.value++;

      // // 根据题型进行相应初始化
      // if (currentQuestion?.type == 3) {
      //   // 滑动打分题
      //   int questionId = currentQuestion!.id!;
      //   if (!userAnswers.containsKey(questionId)) {
      //     if (currentQuestion!.options != null && currentQuestion!.options!.isNotEmpty) {
      //       userAnswers[questionId] = {
      //         'optionId': 5,
      //       };
      //     }
      //   }
      // } else
      clog(
          'userAnswers[currentQuestion?.id ?? 0]    ${userAnswers[currentQuestion?.id ?? 0]}');
      if (currentQuestion?.type == 4) {
        userAnswers[currentQuestion?.id ?? 0] =
            (currentQuestion?.options ?? []).map((item) {
          return item.id ?? 0;
        }).toList();
        update();
      } else if (currentQuestion?.type == 7 &&
          userAnswers[currentQuestion?.id ?? 0] == null) {
        userAnswers[currentQuestion?.id ?? 0] =
            (currentQuestion?.options ?? []).map((item) {
          return 0;
        }).toList();
        clog('daksdkasjd   ${userAnswers[currentQuestion?.id ?? 0]}');
        update();
      } else if (currentQuestion?.type == 3 &&
          (userAnswers[currentQuestion?.id ?? 0]?.firstOrNull ?? 0) == 0) {
        userAnswers[currentQuestion?.id ?? 0] = [5];
        update();
      }
      //   // 排序题
      //   initRankingOptions();
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 5) {
      //   // 图片选择题
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 6) {
      //   // 情绪选择器
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 7) {
      //   // 百分比分配题
      //   // 无需特殊初始化，由PercentageAllocationWidget内部处理
      // }
    } else {
      // 已经是最后一题，提交测试
      submitTest();
    }
  }

  // 前往上一题
  void previousQuestion() {
    if (currentQuestionIndex.value > 0) {
      currentQuestionIndex.value--;
      //
      // // 根据题型进行相应初始化
      // if (currentQuestion?.type == 3) {
      //   // 滑动打分题
      //   int questionId = currentQuestion!.id!;
      //   if (userAnswers.containsKey(questionId)) {
      //     if (userAnswers[questionId] is Map) {
      //       ratingValues[questionId] = userAnswers[questionId]['score'];
      //     } else if (userAnswers[questionId] is int) {
      //       ratingValues[questionId] = userAnswers[questionId];
      //     }
      //   } else {
      //     ratingValues[questionId] = 5;
      //   }
      // } else if (currentQuestion?.type == 4) {
      //   // 排序题
      //   initRankingOptions();
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 5) {
      //   // 图片选择题
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 6) {
      //   // 情绪选择器
      //   initSelectedOptions();
      // } else if (currentQuestion?.type == 7) {
      //   // 百分比分配题
      //   // 无需特殊初始化，由PercentageAllocationWidget内部处理
      // }
    }
  }

  // 提交测试
  Future<void> submitTest() async {
    // 准备答案数据
    List<Map<String, dynamic>> formattedAnswers = [];
    // Map formattedAnswer = {};
    clog('message  ${userAnswers.length}');

    List<ModelTestDetailQuestions> percentageQuestions =
        questions.where((test) => test.type == 7 || test.type == 3).toList();
    // QuestionTypePercentageAllocation
    List<int> percentageQuestionIds =
        percentageQuestions.map((q) => q.id!).toList();

    userAnswers.forEach((questionId, answer) {
      if (percentageQuestionIds.contains(questionId)) {
        ModelTestDetailQuestions? question = percentageQuestions
            .firstWhereOrNull((item) => item.id == questionId);
        if (question?.type == 3) {
          formattedAnswers.add({
            'question_id': questionId,
            'option_ids': (question?.options ?? []).map((q) => q.id!).toList(),
            'score': answer.map((item) => item * 10).toList()
          });
        } else {
          formattedAnswers.add({
            'question_id': questionId,
            'option_ids': (question?.options ?? []).map((q) => q.id!).toList(),
            'score': answer
          });
        }
      } else {
        formattedAnswers.add({'question_id': questionId, 'option_ids': answer});
      }
    });

    HttpResponse response = await HttpManager().post(
      API.testSubmit,
      params: {
        "answers": formattedAnswers,
        "test_id": testId,
        "user_test_id": userTestId,
      },
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      // 跳转到结果页面
      Get.toNamed(AppRoutes.testResultNormal, arguments: {
        'userTestId': userTestId,
      });
    }
  }

  // 获取当前题目序号显示（例如：01/09）
  String getCurrentQuestionNumberDisplay() {
    String current =
        (currentQuestionIndex.value + 1).toString().padLeft(2, '0');
    String total = totalQuestions.toString().padLeft(2, '0');
    return '$current/$total';
  }
}
